<!--<script src="../../vue.config.js"></script>-->
<template>
    <div class="view has-new-background">
        <div class="login-reg-head">
            <cube-tab-bar v-model="selectedLabel" show-slider>
                <cube-tab label="注册" key="register"></cube-tab>
                <cube-tab label="登录" key="login"></cube-tab>
            </cube-tab-bar>
        </div>
        <cube-tab-panels v-model="selectedLabel" class="has-no-background">
            <cube-tab-panel label="注册" key="register">
                <div class="flex tel">
                    <cube-input v-model="tel.value" :placeholder="tel.placeholder" :type="tel.type"></cube-input>
                    <cube-button class="canSendCode" @click="getCodeInRegister" :disable="getCodeInRegisterBtn.disable" :inline="true">
                        {{getCodeInRegisterBtn.text}}
                    </cube-button>
                </div>
                <div class="code">
                    <cube-input v-model="code.value" :maxlength="code.maxlength"
                                :placeholder="code.placeholder"></cube-input>
                </div>
                <div class="pwd">
                    <cube-input v-model="password.value" :placeholder="password.placeholder" :eye="password.eye"
                                :type="password.type"></cube-input>
                </div>
                <div class="flex nickname">
                    <cube-input v-model="nickName.value" :placeholder="nickName.placeholder"></cube-input>
                    <cube-button :inline="true" @click="getSysNickName">随机昵称</cube-button>
                </div>
                <div class="flex nickname">
                    <cube-input v-model="referral.value" :placeholder="referral.placeholder"></cube-input>
                    <div class="scan-code" @click="toScan" v-if="device.status"><i class="iconfont icon-saoma"></i></div>
                </div>


                <cube-radio-group class="flex remark" >
                    <span class="matchmaker-action">
                        <cube-radio v-model="accountType" :option="{label:'',value:'1'}">我要征婚</cube-radio>
                    </span>
                    <span class="matchmaker-action">
                        <cube-radio v-model="accountType" :option="{label:'',value:'2'}">成为红娘</cube-radio>
                    </span>
                </cube-radio-group>

                <!--                    <span>注册遇到问题?</span>-->
                <cube-button class="next-step" @click="toRegister" :disable="!canRegister" :class="{'can-register':canRegister}">
                    下一步
                </cube-button>
                <div class="agreement">
                    注册即表示同意心相依婚恋 <span @click.prevent="toPage('onlineArticle',{title:'terms_of_service'})">注册条款</span>
                </div>
            </cube-tab-panel>
            <cube-tab-panel label="登录" key="login">
                <div class="tel">
                    <cube-input v-model="tel.value" :placeholder="tel.placeholder" :type="tel.type"></cube-input>
                </div>
                <div class="pwd">
                    <cube-input v-model="password.value" :placeholder="password.placeholder" :eye="password.eye"
                                :type="password.type"></cube-input>
                </div>

                <cube-radio-group class="flex remark" >
                    <span class="matchmaker-action">
                        <cube-radio v-model="accountType" :option="{label:'',value:'1'}">我要征婚</cube-radio>
                    </span>
                    <span class="matchmaker-action">
                        <cube-radio v-model="accountType" :option="{label:'',value:'2'}">成为红娘</cube-radio>
                    </span>
                </cube-radio-group>
                <cube-button class="next-step login" :class="{'can-login':canLogin}" @click="toLogin" :disable="!canLogin">
                    登录
                </cube-button>
                <div class="flex remark center">
                    <span @click="toForgetPassword">忘记密码?</span>
                </div>
            </cube-tab-panel>
        </cube-tab-panels>
        <!--        <div class="flex tourist">-->
        <!--            <div class="man">男游客访问</div>-->
        <!--            <div class="woman">女游客访问</div>-->
        <!--        </div>-->
    </div>
</template>

<script lang="ts">
    import {Component, Prop, Vue, Watch} from "vue-property-decorator";
    import VerificationUnit from "@/unit/VerificationUnit";
    import Scene from "@/render/Scene";
    import Http from "@/service/Http";
    import {updateUser} from "@/store/dispatches";
    import CommonUnit from "@/unit/CommonUnit";
    import {InterfaceUser} from "@/interface/InterfaceUser";
    import {Action, State} from "vuex-class";

    @Component({})
    export default class LoginRegister extends Scene {
        private currentValue: string = "/";
        private getCodeAgainTime: number = 60;
        private getCodeInRegisterTimer: any = "";
        private getCodeInRegisterTime: number = 60;
        private selectedLabel: string = "注册";
        private matchmakerLogin: boolean = false;
        private matchmakerReg: boolean = false;
        private accountType: string = "1";
        private isWechatBrowser: boolean = CommonUnit.wechatBrowser();
        private wechatCode: string = "";
        private once: boolean = true;

        @State("UserStore")
        private user!: InterfaceUser;

        @Action("sendMessage")
        private socketSendMessage!: Function;

        @State("DeviceStore")
        private device: any;

        @Watch("$route")
        private onChangeRoute(n: any, o: any): any {
            if (n.query.shareCode) {
                this.setReferral(n.query.shareCode);
            }
        }

        private tel: any = {
            value: "",
            placeholder: "请输入手机号",
            type: "number"
        };

        private code: any = {
            value: "",
            placeholder: "请输入验证码",
            maxlength: 6
        };

        private referral: any = {
            value: "",
            placeholder: "推荐码（选填）",
            maxlength: 20
        };

        private password: any = {
            value: "",
            type: "password",
            placeholder: "请输入6~16位字母/数字密码",
            maxlength: 16,
            eye: {
                open: false,
                reverse: false
            }
        };

        private nickName: any = {
            value: "",
            placeholder: "昵称"
        };

        private created(): void {
            if (!this.device.status) {
                if (this.$route.query.referer === "setting" && localStorage.getItem("reloadTime") === "0") {
                    localStorage.setItem("reloadTime", "1");
                    window.location.href = location.origin + location.pathname;
                }
                if (this.isWechatBrowser) {
                    if (this.$route.query.code) {
                        if (localStorage.getItem("shareCode")) {
                            this.setReferral(String(localStorage.getItem("shareCode")));
                        }
                        this.wechatCode = String(this.$route.query.code);
                    } else {
                        if (this.$route.query.shareCode) {
                            localStorage.setItem("shareCode", String(this.$route.query.shareCode));
                        }
                        this.getWeChatCode(encodeURIComponent( `${location.origin}/wechatAuth.html`));
                    }
                    // const url = document.location.toString();
                    // const hasCode = CommonUnit.getQueryString("code", url);
                    // // const hasCode = url.split("?")[1] && url.split("?")[1].split("&")[0] ? url.split("?")[1].split("&")[0].split("=")[0] === "code" : false;
                    // if (hasCode) {
                    //     this.wechatCode = hasCode;
                    //
                    // } else {
                    //
                    // }
                }
            }
        }

        private get getCodeInRegisterBtn(): any {
            if (this.getCodeInRegisterTime <= 0) {
                clearInterval(this.getCodeInRegisterTimer);
                this.getCodeInRegisterTime = this.getCodeAgainTime;
            }
            const disabled = this.getCodeInRegisterTime !== this.getCodeAgainTime;
            return {
                disabled: disabled,
                text: disabled ? `${this.getCodeInRegisterTime}秒后重发` : "获取验证码",
            };
        };

        private get registerParam(): any {
            const CryptoJS = require("crypto-js");
            return {
                phone: this.tel.value,
                password: CryptoJS.AES.encrypt(CryptoJS.MD5(this.password.value).toString(), CryptoJS.enc.Utf8.parse(this.cryptoKey), {mode: CryptoJS.mode.ECB,}).toString(),
                code: this.code.value,
                nickName: this.nickName.value,
                referral: this.referral.value,
                type: this.accountType,
                wxcode: this.wechatCode,
            };
        }

        private get loginParam(): any {
            const CryptoJS = require("crypto-js");
            return {
                phone: this.tel.value,
                password: CryptoJS.AES.encrypt(CryptoJS.MD5(this.password.value).toString(), CryptoJS.enc.Utf8.parse(this.cryptoKey), {mode: CryptoJS.mode.ECB,}).toString(),
                type: this.accountType,
                wxcode: this.wechatCode,
            };
        }

        private get canRegister(): boolean {
            return VerificationUnit.phone(String(this.tel.value)) && this.code.value.length === 6 && this.password.value.length <= 16 && this.password.value.length >= 6 && this.nickName.value !== "";
        }

        private get canLogin(): boolean {
            return VerificationUnit.phone(String(this.tel.value)) && this.password.value.length <= 16 && this.password.value.length >= 6;
        }

        private mounted(): void {
            this.currentValue = this.$route.path;
            if (this.$route.query.shareCode) {
                this.setReferral(String(this.$route.query.shareCode));
            }
            this.$nextTick(() => {
                this.accountType = "1";
                (<any> this).$bus.$on("scanCode", (text: string) => {
                    const code = CommonUnit.getQueryString("shareCode", text);
                    if (code.length >= 4) {
                        this.redirectTo({
                            name: "loginRegister",
                            query: {
                                shareCode: code
                            }
                        });
                    } else {
                        (<any> this).$createToast({
                            type: "error",
                            txt: `无效推荐码${code}`
                        }).show();
                    }
                });
            });

        }

        private setReferral(code: string): void {
            this.$set(this.referral, "value", code);
            console.log(this.referral);
            // this.referral.value = code;
        }

        private beforeDestroy() {
            (<any> this).$bus.off("scanCode", this.setReferral);
        }

        private getCodeInRegister(): void {
            if (VerificationUnit.phone(String(this.tel.value))) {
                Http.post(this.api.identify, {phone: this.tel.value}).then((res) => {
                    if (res.code === 1) {
                        this.getCodeInRegisterTime--;
                        this.getCodeInRegisterTimer = setInterval(() => {
                            this.getCodeInRegisterTime--;
                        }, 1000);
                    } else {
                        (<any> this).$createToast({
                            type: "error",
                            txt: res.msg
                        }).show();
                    }

                }).catch(() => {
                    (<any> this).$createToast({
                        type: "error",
                        txt: "发送失败"
                    }).show();
                });

            } else {
                (<any> this).$createToast({
                    time: 2500,
                    type: "warn",
                    txt: `${(<any> this).tel.value}不是合法的手机号`
                }).show();
            }

        }

        private getSysNickName(): void {
            Http.get(this.api.nickName).then((res) => {
                if (res.code === 1) {
                    this.nickName.value = res.data.nick_name;
                }
            });
        }

        private toRegister(): void {
            let registerToast = (<any> this).$createToast({
                time: 0,
                type: "loading",
                mask: true,
                txt: "正在注册，请稍后～"
            }).show();
            Http.post(this.api.register, {...this.registerParam}).then((res) => {
                if (res.code === 1) {
                    updateUser({token: res.data.token});
                    try {
                        this.socketSendMessage(JSON.stringify({type: "unbind"}));
                        setTimeout(() => {
                            this.socketSendMessage(JSON.stringify({type: "bind", token: res.data.token}));
                        }, 300);
                    } catch (e) {
                        console.log(e);
                    }
                    Http.get(this.api.getUserInfo, {}, {token: res.data.token}).then((res) => {
                        if (res.code === 1) {
                            let user: any = {...res.data, ...res.data.user_info};
                            delete user.user_info;
                            updateUser(CommonUnit.objectUnderlineToHump(user));
                            if (localStorage.getItem("shareCode")) {
                                localStorage.removeItem("shareCode");
                            }
                            registerToast = (<any> this).$createToast({
                                txt: `注册成功！！请完善头像和性别`,
                                type: "correct",
                                time: 3000,
                                onTimeout: () => {
                                    this.switchTab({
                                        name: "mineAvatarAndSex",
                                        query: {
                                            redirect: this.$route.query["redirect"]
                                        }
                                    });
                                }
                            }).show();
                        } else {
                            registerToast = (<any> this).$createToast({
                                time: 2000,
                                type: "error",
                                txt: `发生错误：${res.msg}`,
                                onTimeout: () => {
                                    if (!this.device.status) {
                                        this.getWeChatCode("https://www.xxyhl.cn/love.html");

                                    }
                                }
                            }).show();
                        }
                    });
                } else {
                    registerToast = (<any> this).$createToast({
                        time: 2000,
                        type: "error",
                        txt: `发生错误：${res.msg}`,
                        onTimeout: () => {
                            if (!this.device.status) {
                                this.getWeChatCode("https://www.xxyhl.cn/love.html");

                            }
                        }
                    }).show();
                }
            }).catch(() => {
                registerToast.hide();
            });
        }

        private toLogin(): void {
            let loginToast = (<any> this).$createToast({
                time: 0,
                type: "loading",
                mask: true,
                txt: "正在登录，请稍后～"
            }).show();
            Http.post(this.api.login, {...this.loginParam}).then((res) => {
                if (res.code === 1) {
                    updateUser({token: res.data.token});
                    try {
                        this.socketSendMessage(JSON.stringify({type: "unbind"}));
                        setTimeout(() => {
                            this.socketSendMessage(JSON.stringify({type: "bind", token: res.data.token}));
                        }, 300);
                    } catch (e) {
                        console.log(e);
                    }
                    Http.get(this.api.getUserInfo, {}, {token: res.data.token}).then((res) => {
                        if (res.code === 1) {
                            let user: any = {...res.data, ...res.data.user_info};
                            delete user.user_info;
                            updateUser(CommonUnit.objectUnderlineToHump(user));
                            loginToast = (<any> this).$createToast({
                                txt: `登录成功！！${user.gender > 0 ? "3秒后返回上一个页面" : "请完善头像和性别"}`,
                                type: "correct",
                                time: 3000,
                                onTimeout: () => {
                                    if (localStorage.getItem("shareCode")) {
                                        localStorage.removeItem("shareCode");
                                    }
                                    if (user.gender > 0) {
                                        this.switchTab({name: "main"});
                                    } else {
                                        this.switchTab({
                                            name: "mineAvatarAndSex",
                                            query: {
                                                redirect: this.$route.query["redirect"]
                                            }
                                        });
                                    }
                                }
                            }).show();
                        } else {
                            loginToast = (<any> this).$createToast({
                                time: 2000,
                                type: "error",
                                txt: `发生错误：${res.msg}`,
                                onTimeout: () => {
                                    this.getWeChatCode("https://www.xxyhl.cn/love.html");
                                }
                            }).show();
                        }
                    });
                } else {
                    loginToast = (<any> this).$createToast({
                        time: 2000,
                        type: "error",
                        txt: `发生错误：${res.msg}`,
                        onTimeout: () => {
                            this.getWeChatCode("https://www.xxyhl.cn/love.html");
                        }
                    }).show();
                }
            }).catch(() => {
                loginToast.hide();
            });
        }

        private toScan() {
            if (this.device.status) {
                QRScanner.prepare((err: any, status: any) => {
                    if (err) {
                        (<any> this).$createToast({
                            time: 1000,
                            type: "error",
                            txt: "授权相机使用被拒绝，请从设置中开启相机权限"
                        }).show();
                    } else if (status.authorized) {
                        this.navigateTo({
                            name: "scanCode",
                            query: {
                                eventName: "scanCode",
                                tips: "请扫描邀请二维码"
                            }
                        });
                    } else {
                        (<any> this).$createToast({
                            time: 1000,
                            type: "授权相机使用被拒绝，请从设置中开启相机权限",
                            txt: err
                        }).show();
                    }
                });
            }
        }

        private toPage(name: string, query: any = {}): any {
            this.navigateTo({
                name: name,
                query: query
            });
        }

        private toForgetPassword() {
            this.navigateTo({
                name: "forgetPassword"
            }, false);
        }
    }
</script>

<style scoped lang="stylus">
    .view
        height 100vh;
        width 100vw;
        background #fff !important;

        .login-reg-head
            height calc(46px + var(--safe-area-inset-top));
            width 100vw;
            padding var(--safe-area-inset-top) 5vw 0 5vw;
            background rgba(255, 255, 255, .5)
            position relative

            &::after
                content '';
                width 100%;
                height 1px;
                left 0;
                bottom 0;
                display block;
                position absolute;
                z-index 2;
                /*transform scaleY(.5);*/
                background #eaeaea;

            >>> .cube-tab-bar
                height 45px;
                margin 0;

            >>> .cube-tab_active
                position relative;
                color $theme-common-color;
                border-bottom none;

                &::after
                    content '';
                    width 100%;
                    height 1px;
                    left 0;
                    bottom 0;
                    display block;
                    position absolute;
                    z-index 100;
                    /*transform scaleY(.5);*/
                    background $theme-common-color !important;

            >>> .cube-tab
                margin-top -1px;
                padding 17px 0 15px 0;
                border-bottom 0 solid $theme-line-color;
                margin 0 30px;

            >>> .cube-tab-bar-slider
                display none;

        >>> .cube-tab-panels
            .cube-tab-panel
                padding 10px 20px;
                height calc(100vh - 46px - var(--safe-area-inset-top))

                > div
                    border-bottom 1px solid $theme-line-color;

                    .cube-input
                        background rgba(255, 255, 255, 0)

                        &::after
                            display none;

                        input.cube-input-field
                            color #111

                            &::-webkit-input-placeholder
                                color: #777;

                div.flex
                    justify-content space-between;
                    align-items center;

                    &.cube-radio-group
                        font-size 16px;
                        background rgba(255, 255, 255, 0)

                        &::after, &::before
                            display none !important

                    >>> .cube-radio
                        font-size 16px;
                        padding 0;

                .cube-radio-ui
                    &::before
                        color $theme-common-color !important

                div.center
                    justify-content center !important;

                div.tel
                    border-bottom 1px solid $theme-line-color;

                    .cube-input

                        &::after
                            display none;

                        .cube-input-field
                            width calc(100vw - 34vw);

                    .cube-btn
                        background-color $theme-common-color;
                        color #fff;
                        border-radius 100px;
                        padding 0px 10px;
                        height 28px;

                div.nickname
                    .cube-input
                        &::after
                            display none;

                        .cube-input-field
                            width calc(100vw - 34vw);

                    .cube-btn
                        background-color #fff;
                        color $theme-common-color;
                        border 1px solid $theme-common-color;
                        border-radius 100px;
                        padding 0px 10px;
                        height 28px;

                div.remark
                    border none;
                    justify-content space-between;
                    color $theme-light-color;
                    margin-top 20px;

                .next-step
                    background-color $theme-common-color !important;
                    opacity .4;
                    color #fff;
                    border-radius 200px;
                    margin-top 20px;

                .agreement
                    border none;
                    margin-top 20px;
                    text-align center;
                    color $theme-viceColor-font;

                    span
                        color $theme-light-color;

                .login
                    margin-top 40px;

            .tourist
                width 100vw;
                position fixed;
                bottom 0px;
                padding 10px 0;
                justify-content space-around;

                div
                    width 40vw;
                    padding 2.5vh 0;
                    text-align center;


                .man
                    color $theme-light-color;
                    border 1px solid $theme-light-color;
                    border-radius 8px;

                .woman
                    color $theme-common-color;
                    border 1px solid $theme-common-color;
                    border-radius 8px;

        .can-register, .can-login
            background $theme-common-color !important;
            opacity 1 !important

    .matchmaker-action
        color $theme-common-color;
        font-size 13px;

        >>> .cube-radio
            color $theme-common-color;
            padding 0
            font-size 15px;

            label
                padding 0;

    .scan-code
        position absolute;
        margin-right 20px;
        right 0
        width 30px;
        height 30px;
        color #333;
        display flex;
        justify-content center;
        align-items center;

    .has-new-background
        background-image url("/assets/images/new-user-background.jpg") !important;
        background-position bottom center !important;
        background-size cover !important;

    .has-no-background
        background rgba(255, 255, 255, 0)
</style>
